package com.yr.log.task;

import code.general.redis.MyJedis;
import com.alibaba.fastjson.JSON;
import com.yr.common.EventModel;
import com.yr.common.EventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class EventConsumer implements InitializingBean, ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);
    private Map<Integer, List<EventHandler>> config = new HashMap<Integer, List<EventHandler>>();
    private ApplicationContext applicationContext;

    private  static ExecutorService executorService = Executors.newFixedThreadPool(3);

    @Autowired
    MyJedis jedis;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, EventHandler> beans = applicationContext.getBeansOfType(EventHandler.class);
        if (beans != null) {
            for (Map.Entry<String, EventHandler> entry : beans.entrySet()) {
                List<EventType> eventTypes = entry.getValue().getSupportEventTypes();

                for (EventType type : eventTypes) {
                    if (!config.containsKey(type.getValue())) {
                        config.put(type.getValue(), new ArrayList<EventHandler>());
                    }
                    config.get(type.getValue()).add(entry.getValue());
                }
            }
        }

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                logger.info("------------------------启动成功");

                while(true) {
                    String message = null;
                    try {
                        String key = "log";
                        List<String> events = jedis.brpop(0, key);
                        for (int i=0;i<events.size();i++) {
                            message = events.get(i);
                            if (message.equals(key)) {
                                continue;
                            }
                            EventModel eventModel = JSON.parseObject(message, EventModel.class);
                            if (!config.containsKey(eventModel.getType())) {
                                logger.error("不能识别的事件");
                                continue;
                            }

                            for (EventHandler handler : config.get(eventModel.getType())) {
//                            handler.doHandle(eventModel);
                                executorService.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        handler.doHandle(eventModel);
                                    }
                                });

                            }
                        }
                    }catch (Exception e){
                        logger.error("------日志解析失败：{}",message,e);
                    }

                }
            }
        });
        thread.start();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
